import { Breadcrumb, Card, Form, Button, Radio, Select, DatePicker, Table, Tag, Space, Modal } from 'antd'
import { Link } from 'react-router-dom'
import { useState, useEffect, useRef } from 'react'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { getChanelList, getArticltList, deleteArticltId } from 'api/login' //引入接口
import defaultImg from 'assets/error.png' // 引入错误图片

export default function ArticltList() {
  const [channels, setChannels] = useState([])
  const [article, setArticle] = useState({})
  // 创建ref对象，用于存放query数据，方便再不同函数内存值和取值
  const queryRef = useRef({})
  // const [pageObj, setPageobj] = useState({ page: 1, per_page: 10 })
  // 定义获取频道函数
  const getChannleHandle = async () => {
    const res = await getChanelList()
    setChannels(res.data.channels)
    console.log(channels)
  }
  // 定义获取文章列表的函数
  const getArticltListFn = async (query) => {
    const res = await getArticltList(query)
    console.log(res.data)
    setArticle(res.data)
  }
  // 组件挂载时  eslint-disable-line是忽略这一行，eslint报错
  useEffect(() => {
    getChannleHandle()
    getArticltListFn()
  }, []) // eslint-disable-line
  const finishHandle = ({ date, channel_id, status }) => {
    console.log({ date, channel_id, status })
    const query = {}
    query.channel_id = channel_id
    query.status = status !== -1 ? status : undefined
    if (date) {
      // 需要把 Moment 对象格式化成字符串
      query.begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      query.end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    }
    for (const key in query) {
      if (query[key] === undefined) {
        // delete 删除对象的键
        delete query[key]
      }
    }
    console.log(query)
    getArticltListFn(query)
    queryRef.current = query
  }
  // 分页时触发
  const pageChange = async (page, pageSize) => {
    console.log('useRef数据', queryRef.current)
    const res = await getArticltList({
      ...queryRef.current,
      page,
      pageSize,
    })
    setArticle(res.data)
  }
  // 删除功能
  const handleDelete = (id) => {
    // Modal 对话框的使用
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章嘛？',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        let params = {}
        await deleteArticltId(params, id)
        getArticltListFn({ ...queryRef.current, page: article.page, per_page: article.per_page })
      },
    })
  }
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ]
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover.images[0] || defaultImg} alt='' style={{ width: 100, height: 60, objectFit: 'cover' }} />
      },
    },
    { title: '标题', dataIndex: 'title' },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        const obj = articleStatus.find((v) => v.id === status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      },
    },
    { title: '发布时间', dataIndex: 'pubdate' },
    { title: '阅读数', dataIndex: 'read_count' },
    { title: '评论数', dataIndex: 'comment_count' },
    { title: '点赞数', dataIndex: 'like_count' },
    {
      title: '操作',
      render: (item) => {
        return (
          <Space>
            <Button type='primary' shape='circle' icon={<EditOutlined />}></Button>
            <Button type='primary' danger shape='circle' icon={<DeleteOutlined />} onClick={() => handleDelete(item.id)}></Button>
          </Space>
        )
      },
    },
  ]
  return (
    <div>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章内容</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* initialValues默认值 */}
        <Form onFinish={finishHandle} initialValues={{ status: -1 }}>
          <Form.Item label='状态' name='status'>
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label='频道' name='channel_id'>
            <Select placeholder='选择文章频道' style={{ width: 200 }} allowClear>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label='日期' name='date'>
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item label=''>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </Form.Item>
        </Form>
        <h3>根据筛选条件共查询到{article.total_count}条结果</h3>
        <Table
          rowKey='id'
          dataSource={article.results}
          columns={columns}
          pagination={{
            position: ['bottomCenter'],
            total: article.total_count,
            onChange: pageChange,
            // 当前页
            current: article.page,
            //
            pageSize: article.per_page,
          }}
        />
        {/* <Pagination showQuickJumper defaultCurrent={pageObj} total={article.total_count} onChange={changePageHandle} /> */}
      </Card>
    </div>
  )
}
